import {
  router,
  addRoutes
} from "@/router";
import {
  getToken
} from "@/utils/auth";
import {
  Toast
} from "@/utils/utils";
import {
  user
} from "@/store/user";

// 全局前置守卫
let hasGetInfo = false;
router.beforeEach(async (to, from, next) => {
  // 获取token 判断有无token 无token就跳转到登录
  let token = getToken();
  if (!token && to.path != "/login") {
    Toast("请先登录", "error");
    return next({
      path: "/login"
    });
  }

  // 防止重复登录
  if (token && to.path == "/login") {
    Toast("请勿重复登录", "error");
    return next({
      path: from.path ? from.path : "/"
    });
  }

  let hasNewRoutes = false;

  // 如果用户登录了，自动获取用户信息，并存储在vuex当中
  if (token && !hasGetInfo) {
    let store = user();
    hasGetInfo = true
    let res = await store.getInfo();
    hasNewRoutes = addRoutes(res.data.menus)
  }

  hasNewRoutes ? next(to.fullPath) : next()
});